#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

&main;

# Generates a sequence of random nucleotids
# Parameter length: the number of nucleotids of the sequence to generate
# Returns: a string with the sequence
sub full_random_seq
{
    my ($length) = @_;
    my $ret_string = '';
    
    my %nucl_hash = (0 => 'a',
                     1 => 'c',
                     2 => 'g',
                     3 => 't');
    
    for(my $i = 0; $i < $length; $i++){
        $ret_string .= $nucl_hash{int(rand(4))}; # the magic `4' is the number of nucleotids
    }
    
    return $ret_string;
}

# Generates a sequence of random nucleotides,
# but with a given proportion.
# This is: the sub will receive a number of every type
# of nucleotide ('a', 'c', 'g' and 't'), and will
# create a random sequence that contains exactly
# the number of each type specified
# Parameter: an array of 4 elements, representing
# the total of 'a', 'c', 'g' and 't' nucleotids.
# Returns: a string with the sequence.
sub proportional_rand
{
    my ($a,$c,$g,$t) = @_;
    my $ret_string = '';
    my $tot = $a + $c + $g + $t;
    
    for(my $i = $tot; $i>0; $i--){
        my $rand_number = 1 + int(rand($i));

        if ($rand_number <= $a){
            $ret_string .= "a";
            $a--;
        } elsif ($rand_number <= $a + $c){
            $ret_string .= "c";
            $c--;
        } elsif ($rand_number <= $a + $c + $g){
            $ret_string .= "g";
            $g--;
        } elsif ($rand_number <= $a + $c + $g + $t){
            $ret_string .= "t";
            $t--;
        } else {
            die "Error in proportional rand()!. Dumping values: '$a' = $a, '$c' = $c, '$g' = $g, '$t' = $t, '$i' = $i, '$rand_number' = $rand_number\n";
        }

    }

    return $ret_string;
}

sub main
{
    if (@ARGV != 5){
        die "I need 4 args: 'a', 'c', 'g, 't' and 'N'. 'a', 'c', 'g' and 't' are the number each nucleotide, 'N' is the number of sequences to generate!";
    }
    my $a = int (shift (@ARGV)) or die "I need the number of 'a' nucleotides!";
    my $c = int (shift (@ARGV)) or die "I need the number of 'c' nucleotides!";
    my $g = int (shift (@ARGV)) or die "I need the number of 'g' nucleotides!";
    my $t = int (shift (@ARGV)) or die "I need the number of 't' nucleotides!";

    my $N = int (shift (@ARGV)) or die "I need the number of sequences to generate!";

    for(my $i = 1; $i <= $N; $i++){
        my $prop_string = proportional_rand($a, $c, $g, $t);

        open(HANDLE, ">random_sequence_$i".".seq") or die "could not open output file: $!";
        print HANDLE $prop_string."\n";
        close (HANDLE);
    }

}

